package com.starbugs.wehcat.controller;

import com.starbugs.wehcat.pojo.Order;
import com.starbugs.wehcat.pojo.Taco1;
import com.starbugs.wehcat.data.JdbcIngredientRepository;
import com.starbugs.wehcat.data.JdbcTacoRepository;
import com.starbugs.wehcat.data.TacoRepository;
import com.starbugs.wehcat.pojo.Ingredient;
import com.starbugs.wehcat.pojo.Taco;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.validation.Valid;

// @Slf4j 在运行时，它会在这个类中自动生成一个SLF4J（Simple LoggingFacade for Java）Logger
// @RequestMapping 是类的注解 GetMapping 是对其细化，是 4.3才出现的

// 类级别的@SessionAttributes能够指定模型对象（如订单属性）要保存在session中，这样才能跨请求使用

/**
 * @author starbooks
 */
@Slf4j
@Controller
@RequestMapping("/design")
@SessionAttributes("order")
public class DesignController {

  private final JdbcIngredientRepository ingredientRepo;
  private TacoRepository designRepo;

  @ModelAttribute(name = "taco")
  public Taco taco() {
    return new Taco();
  }

  // order()方法上的@ModelAttribute注解能够确保会在模型中创建一个Order对象

  @ModelAttribute(name = "order")
  public Order order() {
    return new Order();
  }

  @Autowired
  public DesignController(JdbcIngredientRepository ingredientRepo, JdbcTacoRepository designRepo) {
    this.ingredientRepo = ingredientRepo;
    this.designRepo = designRepo;
  }

  @GetMapping
  public String showDesignForm(Model model) {
    // Model对象负责在控制器和展现数据的视图之间传递数据
    List<Ingredient> ingredients = new ArrayList<>();
    ingredientRepo.findAll().forEach(a -> ingredients.add(a));
    Ingredient.Type[] types = Ingredient.Type.values();
    for (Ingredient.Type type : types) {
      model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients, type));
    }
    return "design";
  }

  private List<Ingredient> filterByType(List<Ingredient> Ingredients, Ingredient.Type type) {
    return Ingredients.stream().filter(x -> x.getType().equals(type)).collect(Collectors.toList());
  }

  @PostMapping
  public String processDesign(@Valid Taco1 design1, Errors errors, @ModelAttribute Order order) {
    log.info(" " + errors);
    if (errors.hasErrors()) {
      return "design";
    }
    // 创建一个新的Taco对象
    Taco design = new Taco();

    // 设置name
    design.setName(design1.getName());

    List<Ingredient> list1 = new ArrayList<>();

    // 创建一个新的 List<Ingredient>
    Ingredient.Type[] types = Ingredient.Type.values();
    for (int a = 0; a < design1.getIngredients().length; a++) {
      String ingredientString = design1.getIngredients()[a];
      String[] ingredientArray = ingredientString.split("/");
      Ingredient.Type t1 = null;
      for (Ingredient.Type t : types) {
        if (t.toString().equals(ingredientArray[2])) {
          t1 = t;
        }
      }
      Ingredient ingredient = new Ingredient(ingredientArray[0], ingredientArray[1], t1);
      list1.add(ingredient);
    }

    design.setIngredients(list1);

    Taco saved = designRepo.save(design);
    order.addDesign(saved);

    return "redirect:/orders/current";
  }
}
